// 检查页面中的视频元素
function checkVideo() {
  var videos = document.querySelectorAll('video');
  return videos.length > 0;
}

// 从URL中提取BV号
function getBvid() {
  var match = location.pathname.match(/\/video\/(BV[\w]+)/);
  return match ? match[1] : null;
}

// 获取B站音频URL
async function getBilibiliAudioUrl() {
  var bvid = getBvid();
  if (!bvid) {
    throw new Error('未找到视频BV号');
  }

  console.log('[INFO] 开始获取音频，BV号:', bvid);

  // 获取cid
  const viewApi = 'https://api.bilibili.com/x/web-interface/view?bvid=' + bvid;
  console.log('[INFO] 请求视频信息:', viewApi);
  
  var pageData = await fetch(viewApi).then(function(r) { return r.json(); });
  
  if (pageData.code !== 0) {
    console.error('[ERROR] 获取视频信息失败:', {
      code: pageData.code,
      message: pageData.message,
      url: viewApi
    });
    throw new Error('获取视频信息失败');
  }
  
  var cid = pageData.data.cid;
  console.log('[INFO] 获取视频信息成功:', {
    bvid: bvid,
    cid: cid,
    title: pageData.data.title,
    duration: pageData.data.duration
  });

  // 获取音频URL
  const playApi = 'https://api.bilibili.com/x/player/playurl?bvid=' + bvid + '&cid=' + cid + '&fnval=16';
  console.log('[INFO] 请求音频地址:', playApi);
  
  var playData = await fetch(playApi, {
    headers: {
      'Referer': 'https://www.bilibili.com'
    }
  }).then(function(r) { return r.json(); });

  if (playData.code !== 0) {
    console.error('[ERROR] 获取音频地址失败:', {
      code: playData.code,
      message: playData.message,
      url: playApi
    });
    throw new Error('获取音频地址失败');
  }

  // 优先使用音频流
  var audioUrl = playData.data.dash?.audio?.[0]?.baseUrl;
  console.log('[INFO] 获取音频流地址:', audioUrl);
  if (!audioUrl) {
    console.error('[ERROR] 未找到音频流:', {
      dash: playData.data.dash,
      durl: playData.data.durl
    });
    throw new Error('未找到音频流地址');
  }

  console.log('[INFO] 获取音频信息成功:', {
    url: audioUrl,
    format: 'audio/mp4',
    quality: playData.data.dash?.audio?.[0]?.id,
    bandwidth: playData.data.dash?.audio?.[0]?.bandwidth,
    duration: playData.data.dash?.duration
  });

  return {
    url: audioUrl,
    format: 'audio/mp4'
  };
}

// 下载音频数据
async function downloadAudio(url) {
  console.log('[INFO] 开始下载音频:', {
    url: url,
    headers: {
      'Referer': 'https://www.bilibili.com',
      'Range': 'bytes=0-',
      'User-Agent': navigator.userAgent,
      'Origin': 'https://www.bilibili.com'
    }
  });
  
  try {
    const response = await fetch(url, {
      headers: {
        'Referer': 'https://www.bilibili.com',
        'Range': 'bytes=0-',
        'User-Agent': navigator.userAgent,
        'Origin': 'https://www.bilibili.com'
      }
    });

    if (!response.ok) {
      console.error('[ERROR] 下载音频失败:', {
        status: response.status,
        statusText: response.statusText,
        headers: Object.fromEntries(response.headers.entries())
      });
      throw new Error('下载音频失败: ' + response.status);
    }
    else {
      console.log('[INFO] 下载音频成功:', {
        status: response.status,
        statusText: response.statusText,
        headers: Object.fromEntries(response.headers.entries())
      });
    }

    const blob = await response.blob();
    console.log('[INFO] 下载完成:', {
      size: blob.size,
      type: blob.type,
      lastModified: blob.lastModified
    });
    
    // 验证数据大小
    if (blob.size < 1000) {
      console.error('[ERROR] 音频数据异常:', {
        size: blob.size,
        type: blob.type
      });
      throw new Error('音频数据异常: ' + blob.size + ' bytes');
    }
    
    return blob;
  } catch (error) {
    console.error('[ERROR] 下载音频失败:', error);
    throw error;
  }
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log('[INFO] 收到消息:', request.type);
  
  if (request.type === 'CHECK_VIDEO') {
    var hasVideo = checkVideo();
    console.log('[INFO] 检查视频结果:', hasVideo);
    sendResponse({ hasVideo: hasVideo });
  } else if (request.type === 'EXTRACT_AUDIO') {
    console.log('[INFO] 开始提取音频: EXTRACT_AUDIO')
    getBilibiliAudioUrl()
      .then(async function(audioInfo) {
        try {
          console.log('[INFO] 获取音频URL成功:', audioInfo.url);
          
          // 下载音频
          const blob = await downloadAudio(audioInfo.url);
          console.log('[INFO] 音频blob大小:', blob.size);
          
          // 转换为ArrayBuffer
          const arrayBuffer = await blob.arrayBuffer();
          
          // 转换为普通数组以便传输
          const uint8Array = new Uint8Array(arrayBuffer);
          const array = Array.from(uint8Array);
          
          console.log('[INFO] 准备发送数据:', {
            arraySize: array.length,
            originalSize: blob.size
          });
          
          // 发送到后台
          var speech_text = "";
          chrome.runtime.sendMessage({
            type: 'SEND_TO_BACKEND',
            audioData: {
              array: array,
              type: audioInfo.format,
              filename: 'audio.mp4',
              size: blob.size
            }
          }, function(response) {
            console.log('[INFO] 后台处理结果:', response);
            if (response.success & response.data?.status == "success"){
              speech_text = response.data.text;
              console.log('[INFO] sendMessage TEXT_OPTIMIZE:', speech_text);
              chrome.runtime.sendMessage({
                type: 'TEXT_OPTIMIZE',
                data: {
                  text: speech_text
                }
              }, function(response) {
                console.log('[INFO] content optimize后台处理结果:', response)
                sendResponse({
                  success: true,
                  data: response.data
                })
              });
            }
            else
            {
              console.error('[ERROR] optimize后台处理失败:', optimize_response);
            }
          });

          // 同时下载一个副本用于验证
          const bvid = getBvid();
          const filename = (bvid || 'audio') + '.mp4';
          const downloadUrl = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = downloadUrl;
          a.download = filename;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          URL.revokeObjectURL(downloadUrl);
          
        } catch (error) {
          console.error('[ERROR] 处理音频失败:', error);
          sendResponse({
            success: false,
            error: error.message
          });
        }
      })
      .catch(function(error) {
        console.error('[ERROR] 提取音频失败:', error);
        sendResponse({
          success: false,
          error: error.message
        });
      });
    return true; // 保持消息通道开启
  }
});

// 通知插件已加载
console.log('[INFO] Content script已加载'); 